package com.lmt.thread;

/**
 * Created by luomingtao on 2021-03-04
 * 使用 wait/notify
 */
public class PrintABCUsingWaitNotify {
    private int state;
    private int times;
    private static final Object lock = new Object();

    public PrintABCUsingWaitNotify(int times) {
        this.times = times;
    }

    public void printLetter(String name, int targetNum) {
        for (int i = 0; i < times; i++) {
            synchronized (lock) {
                while (state % 3 != targetNum) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                state++;
                System.out.println(name);
                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) {

        PrintABCUsingWaitNotify printABC = new PrintABCUsingWaitNotify(3);

        new Thread(() -> {
            printABC.printLetter("B", 1);
        }, "B").start();

        new Thread(() -> {
            printABC.printLetter("A", 0);
        }, "A").start();

        new Thread(() -> {
            printABC.printLetter("C", 2);
        }, "C").start();
    }
}
